class UsersController < ApplicationController

      before_filter :login_required, :only=>['welcome', 'change_password', 'hidden']
  # GET /users
  # GET /users.json
  def index
    @users = User.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render :json => @users }
    end
  end
  def show
      @user = User.find(params[:id])
  end
    
  def new
      @title = "Sign up"
  end
    
  def signup
	@user = User.new(params[:user])
    if @user.authority == "manage123"
        @user.authority = "manager"
    else
        if @user.authority == "adminboss"
            @user.authority = "admin"
        else
            @user.authority = "user"
        end
    end
    
	if request.post?
	  if @user.save
	    session[:user] = User.authenticate(@user.email, @user.password)
	    flash[:message] = "Signup successful"
	    #Notification.welcome_email(@user).deliver
		redirect_to edit_url
      else
	    flash[:warning] = "Signup unsuccessful"
		redirect_to signup_url
      end
    end
  end

  def login
      if request.post?
	 if session[:user] = User.authenticate(params[:user][:login], params[:user][:password])
            flash[:message] = "Login successful"
            redirect_to welcome_path
         else
	     flash[:warning] = "Incorrect email/password combination"
         end
      end
  end

  def logout
      session[:user] = nil
      flash[:message] = 'Logged out'
      redirect_to :action => 'login'
  end

  def forgot_password
      if request.post?
      	 u = User.find_by_email(params[:user][:email])
	 if u and u.send_new_password
	    flash[:message] = "A new password has been sent by email."
	    redirect_to :action=> 'login'
	 else
	    flash[:warning] = "Couldn't send password"
	 end
      end
  end

  def change_password
      @user=session[:user]
	  if @user == nil
		 redirect_to :controller => 'user', :action => 'login'
	  end
      if request.post?
      	@user.update_attributes(:password=>params[:user][:password], :password_confirmation => params[:user][:password_confirmation])
        if @user.save
			flash[:notice]="Password saved"
		else
			flash[:warning]="Error changing password"
		end
      end
  end

  def welcome
  end
  
  def hidden
  end	 	   

  # DELETE /users/1
  # DELETE /users/1.json
  def destroy
    @user = User.find(params[:id])
    @invitee = InviteeList.find_by_user_ids(@user.id)
     
    @user.destroy
	if @invitee != nil
		@invitee.destroy 
	end

    respond_to do |format|
      format.html { redirect_to users_url }
      format.json { head :no_content }
    end
  end
  
  def edit
      @user=session[:user]
	  if @user == nil
		 redirect_to :controller => 'user', :action => 'login'
	  end
      if request.post?
      	@user.update_attributes(params[:user])
        if @user.save
			flash[:notice]="Profile saved"
			redirect_to '/users/'+session[:user].id.to_s
		else
			flash[:warning]="Error saving profile"
		end
      end
  end
end
